package com.resou.reader.mine.setting;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.glong.reader.cache.Cache;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.resou.reader.IMainContract;
import com.resou.reader.MainPresenter;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.assist.WebActivity;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.base.v.BaseActivity;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.dialog.DialogManager;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.reader.autopay.AutoPayActivity;
import com.resou.reader.reader.utils.SpUtils;
import com.resou.reader.utils.CacheUtils;
import com.resou.reader.utils.DeviceUtils;
import com.resou.reader.utils.MarketUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.SystemUtil;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.UserUtil;
import com.resou.reader.utils.downupdata.DownloadListener;
import com.resou.reader.utils.downupdata.DownloadUtil;
import com.resou.reader.utils.eventbus.LoadBookEvent;
import com.resou.reader.utils.eventbus.LogoutEvent;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.utils.log.LogUtil;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SettingActivity extends ResouBaseActivity<MainPresenter> implements SignOutDialog.OnSignOutInteractionListener, IMainContract.IMainView {
    private static final String TAG = "SettingActivity";

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, SettingActivity.class));
    }

    String filePath = "/storage/emulated/0/DCIM/Camera/IMG_20170823_114448_HHT_1531896769601.jpg";
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.rlClearCache)
    RelativeLayout rlClearCache;
    @BindView(R.id.rlUpdate)
    RelativeLayout rlUpdate;
    @BindView(R.id.tvCache)
    TextView tvCache;
    @BindView(R.id.tvResouVersion)
    TextView tvResouVersion;
    @BindView(R.id.btnLoginOut)
    Button btnLoginOut;
    private SignOutDialog mOutDialog;
    private ClearCacheDialog mClearCacheDialog;
    private AlertDialog.Builder builder = null;
    private AlertDialog dialog = null;
    ProgressBar mProgressBar;
    private boolean startDownload = false;
    View view;


    @Override
    protected void initView() {
        tvTitle.setText("设置");
        try {
            tvCache.setText("清除浏览缓存（" + CacheUtils.getTotalCacheSize(this) + ")");
        } catch (Exception e) {
            e.printStackTrace();
        }
        PackageManager manager = getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            tvResouVersion.setText(String.valueOf(" V" + info.versionName));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (UserInstance.isTourist()) {
            btnLoginOut.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initPresenter() {
        mPresenter = new MainPresenter(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    public void retryRefreshData() {

    }


    @Override
    public void onCancelClicked() {
        mOutDialog.dismiss();
    }

    @Override
    public void onCompleteClicked() {
        showProgress();
        UserInstance.setLoginData(null);
        UserInstance.setToken("");
//        LitePalHelper.clearBooks();
        SpUtils.clearLoginState(this);
        mOutDialog.dismiss();
        mPresenter.touristLogin(DeviceUtils.getAndroidId(this));
    }


    @Override
    protected void initStatusBar() {

    }

    @OnClick({R.id.ivBack, R.id.rlAutoPay, R.id.rlLike, R.id.rlClearCache, R.id.rl_AboutResou, R.id.rl_ResouVersion, R.id.rlPrivacy, R.id.rlAgreement, R.id.btnLoginOut, R.id.rlUpdate})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.rlAutoPay:
                AutoPayActivity.start(this);
                break;
            case R.id.rlLike:
                MarketUtils.launchAppDetail(this, getPackageName(), null);
                break;
            case R.id.rlClearCache:
                mClearCacheDialog = ClearCacheDialog.newInstance();
                mClearCacheDialog.setInteractionListener(new ClearCacheDialog.OnSignOutInteractionListener() {
                    @Override
                    public void onCancelClicked() {
                        mClearCacheDialog.dismiss();
                    }

                    @Override
                    public void onCompleteClicked() {
                        CacheUtils.clearAllCache(getApplicationContext());
                        mClearCacheDialog.dismiss();
                        try {
                            tvCache.setText("清除浏览缓存（" + CacheUtils.getTotalCacheSize(getApplicationContext()) + ")");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                mClearCacheDialog.show(getSupportFragmentManager(), "clearDialog");
                break;
            case R.id.rl_AboutResou:
                WebActivity.startActivity(this, "https://m.resouxs.com/about?app=app", getResources().getString(R.string.about_resou));
                break;
            case R.id.rl_ResouVersion:
                break;
            case R.id.rlPrivacy:
                WebActivity.startActivity(this, "https://m.resouxs.com/login/privacy?app=app", "隐私协议");
                break;
            case R.id.rlAgreement:
                WebActivity.startActivity(this, "https://m.resouxs.com/login/protocol?app=app", "用户协议");
                break;
            case R.id.btnLoginOut:
                mOutDialog = SignOutDialog.newInstance();
                mOutDialog.setInteractionListener(this);
                mOutDialog.show(getSupportFragmentManager(), "outDialog");
                break;
            case R.id.rlUpdate:
                mPresenter.updataVersion();
                break;
        }
    }

    public void setToastShow() {
        Toast.makeText(ReSouApplication.getRSApplication(), "当前已是最新版本", Toast.LENGTH_LONG).show();
    }

    @Override
    public Activity getContext() {
        return this;
    }

    public void InstallApk(String downloadApk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(downloadApk);
        LogUtil.d(TAG, "安装路径==" + downloadApk);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(getContext(), "com.resou.reader.fileprovider", file);
//            Uri apkUri = FileProvider.getUriForFile(getActivity(),
//                    SystemUtil.getPackageName(getActivity()) + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    @Override
    public void autoLoginSuccess(LoginData data) {

    }

    @Override
    public void autoLoginFailed(int reason) {

    }

    @Override
    public void touristSuccess() {
        dissLoading();
        //登出
        MobclickAgent.onProfileSignOff();
        Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show();
        /**
         * 同步本地书架到服务器
         */
//        EventBus.getDefault().post(new Message());
        EventBus.getDefault().post(new LoadBookEvent());
        EventBus.getDefault().post(new LogoutEvent());
        finish();
    }

    /**
     * 显示更新弹窗
     */
    @Override
    public void showUpdate(String url) {
        mPresenter.showUpdataDialog(dialog, builder, url);
    }

    @Override
    public void initData() {

    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {
        if (mPresenter == null) {
            mPresenter = new MainPresenter(this);
        }
    }

    @Override
    public void showError(Throwable throwable) {
        ToastUtil.makeShortToast("网络异常");
    }

    @Override
    public void showEmpty() {

    }
}
